/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useEffect, useState, useCallback, useMemo } from 'react';
import PageHeaderLayout from '@/layouts/PageHeaderLayout';
import { connect } from 'dva';
import { debounce } from 'lodash';
import { Alert, Row, Col, Button, Table, Popconfirm, Form, Modal, Input } from 'antd';
import styles from './style.less';

const FormItem = Form.Item;

const formItemLayout = {
  labelCol: {
    xs: { span: 6 },
  },
  wrapperCol: {
    xs: { span: 18 },
  },
};

const messageContent = (
  <div>
    <p>
      1、是否需要配置？配置后能够更加稳定的实现共配上传，请尽可能的配置多条共配加速器密钥，并将加速器软件保持在线状态。加速器软件能安装在任何能上网的电脑上，一台电脑可获取一条密钥。
    </p>
    <p>2、共配加速器软件如何下载安装和获取密钥？</p>
    <p>a）准备一台电脑已联网（win7或以上操作系统）</p>
    <p>
      b）下载共配加速器并安装，下载地址：
      <a target="_blank" rel="noreferrer" href="https://renew.kuaidihelp.com/0/KBGPSetup.exe">
        https://renew.kuaidihelp.com/0/KBGPSetup.exe
      </a>
    </p>
    <p>c）安装完毕，启动程序后，打开“绑定”-“访问密钥”即可获取密钥</p>
    <p>d）将获取到的密钥复制，并维护到下方处，同时保持加速器软件处于打开状态即可</p>
  </div>
);

const PrintKey = ({ dispatch, list = [], addLoading, loading, freshLoading, form }) => {
  const { validateFields, getFieldDecorator } = form;
  const [visible, setVisible] = useState(false);

  useEffect(
    () => {
      getList();
    },
    [getList],
  );

  const getList = useCallback(
    () => {
      dispatch({
        type: 'printKey/getPrintKeyList',
      });
    },
    [dispatch],
  );

  const onDelet = useCallback(
    id => {
      dispatch({
        type: 'printKey/deletePrintKey',
        payload: {
          id,
        },
      }).then(() => {
        getList();
      });
    },
    [dispatch, getList],
  );

  const columns = useMemo(
    () => [
      {
        title: '编号',
        dataIndex: 'id',
        key: 'id',
        align: 'center',
        width: 100,
      },
      {
        title: '加速器名称',
        dataIndex: 'name',
        key: 'name',
        align: 'center',
        width: 250,
      },
      {
        title: '加速器密钥',
        dataIndex: 'key',
        key: 'key',
        align: 'center',
        width: 250,
      },
      {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        align: 'center',
        width: 150,
        render: status => {
          switch (status) {
            case '1':
              return '在线';
            case '2':
              return '离线';
            case '3':
              return '失效';
            default:
              return '--';
          }
        },
      },
      {
        title: '操作',
        align: 'center',
        width: 150,
        render: (_, record) => (
          <Popconfirm title="确定删除该密钥？" onConfirm={() => onDelet(record.id)}>
            <a>删除</a>
          </Popconfirm>
        ),
      },
    ],
    [onDelet],
  );

  const onOk = useCallback(
    () => {
      validateFields(err => {
        if (err) return;
        getList();
        setVisible(false);
      });
    },
    [validateFields, getList],
  );

  const validator = useCallback(
    async (rule, value, callback) => {
      const spaceTest = /^\S*$/;
      const hasSpace = spaceTest.test(value);
      if (!value) {
        callback();
        return;
      }
      if (!hasSpace) {
        callback('密钥不能包含空格！');
        return;
      }
      const result = await dispatch({
        type: 'printKey/addPrintKey',
        payload: {
          secretKey: value,
        },
      });
      if (result.code > 0) {
        callback(result.msg);
      }
      callback();
    },
    [dispatch],
  );

  const onRefresh = useCallback(
    debounce(
      () => {
        dispatch({
          type: 'printKey/refreshStatus',
        }).then(() => {
          getList();
        });
      },
      300,
      {
        leading: true,
        trailing: false,
      },
    ),
    [],
  );

  return (
    <PageHeaderLayout title="共配加速器">
      <div className={styles.main}>
        <Alert message={messageContent} style={{ marginBottom: 20 }} />
        <Row type="flex" gutter={[40, 0]}>
          <Col>
            <Button loading={addLoading} type="primary" onClick={() => setVisible(true)}>
              新增密钥
            </Button>
          </Col>
          <Col>
            <Button loading={freshLoading} type="primary" onClick={onRefresh}>
              刷新状态
            </Button>
          </Col>
        </Row>
        <Table
          style={{ marginTop: 20 }}
          rowKey="id"
          pagination={false}
          loading={loading}
          dataSource={list}
          columns={columns}
          scroll={{ x: 1000 }}
        />
        <Modal
          destroyOnClose
          confirmLoading={addLoading}
          title="新增密钥"
          visible={visible}
          okText="新增"
          onOk={onOk}
          onCancel={() => setVisible(false)}
        >
          <Form layout="inline" {...formItemLayout}>
            <FormItem label="加速器密钥" style={{ width: '100%' }}>
              {getFieldDecorator('key', {
                rules: [{ required: true, message: '密钥不能为空！' }, { validator }],
                validateTrigger: 'onSubmit',
              })(<Input placeholder="请输入加速器密钥" allowClear />)}
            </FormItem>
          </Form>
        </Modal>
      </div>
    </PageHeaderLayout>
  );
};

export default connect(({ loading, printKey }) => ({
  list: printKey.list,
  loading: loading.effects['printKey/getPrintKeyList'],
  freshLoading: loading.effects['printKey/refreshStatus'],
  addLoading: loading.effects['printKey/addPrintKey'],
}))(Form.create()(PrintKey));
